define(['jquery',
         'global',
         'module/util',
         'bootbox.min',
		 'underscore',
		 'page/isbnmanage/editor/isbn_order_module',
		 'page/isbnmanage/editor/isbn_page_module',
         'bootstrap-datetimepicker.zh-CN',
         'bootstrap-datetimepicker',
         'bootstrap-fileinput_zh',
         'bootstrap-fileinput',
         'module/ajax',
         'jquery-weui',
         'bootstrap',
         'pixeladmin'], 
function($, global, util, bootbox, _, IsbnOrder, IsbnPage){
	var IsbnInformation = {
		doSave : function(index) {// 数据保存和修改
			$.ajax({
		        url : global.context + '/web/isbnSaveAndUpdate/informationSaveAndUpdate',
		        data : JSON.stringify(IsbnInformation.dtoList[index]),
	            type : 'POST',
	            dataType : 'json',
	            contentType : 'application/json;charset=utf-8',
		        success : function(result) {
		        	if(result.code == "NACK") {
			        	$.growl.warning({title:"提示",message: "保存失败！"});
		        	} else {
			        	$.growl.warning({title:"提示",message: "保存成功！"});
		        	}
		        },
		        error : function(e) {
		        	$.growl.warning({title:"提示",message: "保存失败！"});
		        }
			});		
		},
		doGetHtmlData : function(index) {
			var root = $("#INFO_PANEL_" + IsbnInformation.dtoList[index].id);
			root.find(IsbnInformation.inputConfig).each(function() {
				IsbnInformation.dtoList[index][this.name] = this.value;
			});
		},
		//-------------------------------基本信息加载和操作开始----------------------------------
		doLoad : function(obj) {// 该方法开始加载界面，打开页面检查是否有barcode，如果有则查询，没有则新建
			if(!obj || !obj.root || obj.root.length == 0 || !obj.barcode || obj.barcode.length == 0) {
				$.alert("不能缺少基本参数！！！");
	        	if(obj && obj.error) obj.error();
				return false;
			}
			var _obj = util.copyBean(obj, {
				beforeSend : function() {
					$("#" + obj.root).find(".weui-infinite-scroll").show();
				},				
				success : function(result){//重写success
					if(result && result.code == "SUCCESS") {
	        			if($.isEmptyObject(result.data)) {
	        				IsbnInformation.doAddData(obj);
	        			} else {
	        				obj.data = result.data;
	    					IsbnInformation.doCreateHtml(obj);
	        			}
			        	if(obj && obj.success) obj.success();
	        		} else {
						$.alert("加载数据出现错误请重试！！！");
	        		}
					if(obj && obj.success) obj.success();
				}, 
				error : function(result) {//重写error
					$.alert("加载数据出现错误请重试！！！");
					if(obj && obj.error) obj.error();
				}, 
				complete : function(result) {
					$("#" + obj.root).find(".weui-infinite-scroll").hide();
				}
			});
			IsbnInformation.doGetData(_obj);
		},
		doAddData : function(obj) {// 新建作业本
			if(!obj || !obj.root || obj.root.length == 0 || !obj.barcode || obj.barcode.length == 0) {
				$.alert("不能缺少基本参数！！！");
	        	if(obj && obj.error) obj.error();
				return false;
			}
			var _obj = util.copyBean(obj, {
				success : function(result){//重写success
					obj["data"] = [result.data];
					IsbnInformation.doCreateHtml(obj);
					if(obj && obj.success) obj.success();
				},
				error : function(result) {//重写error
					$.alert("新增信息出现错误请重试！！！");
					$("#info-infinite-preloader").hide();
					if(obj && obj.error) obj.error();
				}
			});
			IsbnInformation.doGetNewOne(_obj);
		},
		doCreateHtml : function(obj) {
			var render = _.template($("#isbnInformationTemplate").html());
			for(var i in obj.data) {
				var dto = obj.data[i];
				var index = $(".isbn-info").length;
				var renderHtml = render({index : index, id : dto.id, barcode : dto.barcode});
				$("#" + obj.root).append(renderHtml);// 加载页面
				IsbnInformation.doLoadHtmlData(index, dto);
				IsbnInformation.managerJudge(dto.id);
			}
		},
		doLoadHtmlData : function(index, dto) {
			var root = $("#INFO_PANEL_" + dto.id);
			if(!IsbnInformation.dtoList[index]) {// 加载数据到变量
				IsbnInformation.dtoList[index] = dto;
			}
			IsbnInformation.doLoadSelect(dto.id);// 加载下拉列表
			IsbnInformation.doInitFileInput(dto);
			root.find(IsbnInformation.inputConfig).val(function() {
				return dto[$(this).attr('name')];
			});
		},
		doLoadSelect : function(id) {// 这里配置需要加载的选择框
			IsbnInformation.initSelect(id, "type", "作业本类型", "HOMEWORK_TYPE");
			IsbnInformation.initSelect(id, "subject", "学科", "SUBJECT");
			IsbnInformation.initSelect(id, "grade", "年级", "GRADE");
			IsbnInformation.initSelect(id, "term", "学期", "TERM");
			IsbnInformation.initSelect(id, "edition", "版本", "EDTION");
			IsbnInformation.initSelect(id, "status", "ISBN信息状态", "ISBN_INFORMATION_STATUS");
			IsbnInformation.initSelect(id, "hasAnswer", "是不是仅答案", "ISBN_HAS_ANSWER");
			IsbnInformation.initSelect(id, "validation", "审定状态", "ISBN_VALIDATION");
			
		},
		doGetNewOne : function(obj) {// 查询基本数据
			$.ajax({
		        url : global.context + '/web/isbninformation/newInformation',
		        data : util.stringify_aoData({barcode : obj.barcode}),
	            type : 'POST',
	            dataType : 'json',
	            contentType: 'application/json; charset=UTF-8',
	            beforeSend : function() {
		        	if(obj && obj.beforeSend) obj.beforeSend();
	            },
		        success : function(result) {
			        if(obj && obj.success) obj.success(result);
		        },
		        error : function(result) {
		        	if(obj && obj.error) obj.error(result);
		        },
	            complete: function(result){
		        	if(obj && obj.complete) obj.complete(result);
	            }
			});
		},
		doGetData : function(obj) {// 查询基本数据
			$.ajax({
		        url : global.context + '/web/isbninformation/getIsbnInformation',
		        data : {barcode : obj.barcode, isbnInformationId : obj.isbnInformationId},
	            type : 'POST',
	            dataType : 'json',
	            beforeSend : function() {
		        	if(obj && obj.beforeSend) obj.beforeSend();
	            },
		        success : function(result) {
			        if(obj && obj.success) obj.success(result);
		        },
		        error : function(result) {
		        	if(obj && obj.error) obj.error(result);
		        },
	            complete: function(result){
		        	if(obj && obj.complete) obj.complete(result);
	            }
			});
		},
		doInitFileInput : function(dto) {// 数据加载完成后处理页面事件
			var root = $("#INFO_PANEL_" + dto.id);
			var options = {
			    uploadUrl: global.context + '/web/isbnSaveAndUpdate/uploadFile/'+dto.id+'/0', // server upload action
			    language: 'zh',
			    uploadAsync: true,
			    minFileCount: 1,
			    maxFileCount: 1,
			    browseOnZoneClick: true,
			    overwriteInitial: true,
			    initialPreviewAsData: true,
			    initialPreviewFileType: 'image', 
			    initialPreview : [], 
			    initialPreviewConfig : [],
			};
			if(dto.coverImageUrl) {
				var deleteUrl = global.context + '/web/isbnSaveAndUpdate/deleteCover';
				var index = dto.coverImageUrl.lastIndexOf("@") > -1 ? dto.coverImageUrl.lastIndexOf("@") : dto.coverImageUrl.lastIndexOf("/");
				var endIndex = (dto.coverImageUrl.lastIndexOf("?") > -1 ? dto.coverImageUrl.lastIndexOf("?") : dto.coverImageUrl.length);
				var name = dto.coverImageUrl.substring(index + 1, endIndex);
				var url = dto.coverImageUrl.slice(0, 4) == "http" ? dto.coverImageUrl : (global.checkAnswerImgHost + dto.coverImageUrl);
				options.initialPreview.push(url);
				options.initialPreviewConfig.push({caption : name, size : "", width: "250px", url : "", key : "{root : '" + this.id + "', barcode : '" + dto.barcode + "', isbnInformationId:"  + dto.id + ", imgUrlList:['" + url + "']}"});			                        
			}
			root.find("#cover-input-" + dto.id).fileinput(options);
		},
		toEditor : function(id) {//打开编辑
			$("#ISBN_INFO_" + id).find(IsbnInformation.inputConfig).each(function() {
				$(this).attr("readonly", false).attr("disabled", false);
			});
			$("#editorInfoBtn_" + id).hide();
			$("#saveInfoBtn_" + id).show();
			$("#cancelEditorInfoBtn_" + id).show();
			this.managerJudge(id);
		},
		toCancelEditor : function(id) {//关闭编辑
			$("#ISBN_INFO_" + id).find(IsbnInformation.inputConfig).each(function() {
				$(this).attr("readonly", true).attr("disabled", true);
			});
			$("#cancelEditorInfoBtn_" + id).hide();
			$("#saveInfoBtn_" + id).hide();
			$("#editorInfoBtn_" + id).show();
		},
		// 权限处理
		managerJudge : function(id) {
			var index = $("#INFO_PANEL_" + id).attr("info-index"), status = IsbnInformation.dtoList[index].status, workType = $("#workType").val();
			if(workType && id){
				var html = '<div class="form-group col-sm-12">';
				if("buy" == workType){
					if("0" == status){
						//可执行操作 【可填充信息填充完成】
						html += '<a style="cursor:pointer;" class="domethod" data-method="informationFillCando" data-isbninformationid="'+id+'">可填充信息填充完成</a>&nbsp;&nbsp;&nbsp;';
					}
				}else if("complete" == workType){
					if("1" == status){
						//可执行操作 【已完善信息】
						html += '<a style="cursor:pointer;" class="domethod" data-method="informationFillComplete" data-isbninformationid="'+id+'">已完善信息</a>&nbsp;&nbsp;&nbsp;';
					}else if("2" == status){
						//可执行操作 【图片已上传】
						html += '<a style="cursor:pointer;" class="domethod" data-method="pageFillComplete" data-isbninformationid="'+id+'">图片已上传</a>&nbsp;&nbsp;&nbsp;';
					}
				}else if("publish" == workType){
					if("3" == status){
						//可执行操作 【已审核】
						html += '<a style="cursor:pointer;" class="domethod" data-method="judgeComplete" data-isbninformationid="'+id+'">已审核</a>&nbsp;&nbsp;&nbsp;';
						//可执行操作 【废弃】
						html += '<a style="cursor:pointer;" class="domethod" data-method="drop" data-isbninformationid="'+id+'">废弃</a>&nbsp;&nbsp;&nbsp;';
					}else if("4" == status){
						//可执行操作 【已发布】
						html += '<a style="cursor:pointer;" class="domethod" data-method="publish" data-isbninformationid="'+id+'">发布</a>&nbsp;&nbsp;&nbsp;';
					}else if("5" == status){
						//可执行操作 【取消发布】
						html += '<a style="cursor:pointer;" class="domethod" data-method="unpublish" data-isbninformationid="'+id+'">取消发布</a>&nbsp;&nbsp;&nbsp;';
					}
				}
				html += '</div>';
				$("#ISBN_MANAGER_" + id).html(html);
			}
			$("input[name='barcode'], select[name='status']").attr("readonly", true).attr("disabled", true);		
		},
		doBusiness : function(domethod, isbninformationid) {
	        $.ajax({
	            type: "POST",
	            url: global.context +"/web/business/"+method,
	            data: util.stringify_aoData({
	                isbnInformationId : isbninformationid
	            }),
	            contentType: 'application/json; charset=UTF-8',
	            dataType:"json",
	            async: false,  
	            success : function(data) {
	            },
	            error : function() {
	            }
	        });
		},
		doDeleteCover : function(obj) {
			$.ajax({
		        url : global.context + '/web/isbnSaveAndUpdate/deleteCover/' + obj.isbnInformationId,
	            type : 'POST',
	            dataType : 'json',
	            beforeSend : function() {
		        	if(obj && obj.beforeSend) obj.beforeSend();
	            },
		        success : function(result) {
		        	if(obj && obj.success) obj.success(result);
		        },
		        error : function(result) {
		        	if(obj && obj.error) obj.error(result);
		        },
				complete : function(result) {
		        	if(obj && obj.complete) obj.complete(result);
				}
			});
		},
		initSelect : function(id, name, nameDesc, dictName) {// 加载下拉框
			util.selectPadding({
				id : $("#ISBN_INFO_" + id).find("select[name='"+ name +"']"),
				data : global.dict[dictName],
				firstValue : '',
				firstName : '请选择' + nameDesc
			});
		},
		//--------------------基本信息加载和操作结束--------------------------------
		
		// 绑定页面初始化事件开始
		bindEvent : function() {
			$("body").on('click','#addTextBook',function(){
				IsbnInformation.doAddData();
			});
			$("body").on('click','.editorInfoBtn',function(){
				IsbnInformation.toEditor($(this).attr("info-id"));
			});
			$("body").on('click','.cancelEditorInfoBtn',function(){
				IsbnInformation.toCancelEditor($(this).attr("info-id"));
			});
			$("body").on('click','.expandOrder',function(){
				IsbnInformation.doLoadOrder($(this).attr("info-id"));
				return false;		
			});
			$("body").on('click','.expandPage',function(){
				IsbnInformation.doLoadPage($(this).attr("info-id"));
				return false;		
			});
			$("body").on('click','.kv-file-remove',function(){
				var datKey = $(this).attr("data-key");
				if(datKey) {
					var data = eval('(' + datKey + ')');//字符串转对象
					data.success = function(result) {
						if(result && result.code == "ACK") {
							$("#" + data.root).find(".fileinput-remove").click();
						}
					}
					$.confirm({
					  title: '确认删除？',
					  text: '你确定需要删除该图片？',
					  onOK: function () {
						  IsbnInformation.doDeleteCover(data);
					  },
					  onCancel: function () {
					  }
					});
				}
			});
			$("body").on('click','.saveInfoBtn',function(){
				var index = $(this).attr("info-index");
				IsbnInformation.doGetHtmlData(index);
				$.confirm({
				  title: '确认保存？',
				  text: '你确定需要保存数据？',
				  onOK: function () {
					  IsbnInformation.doSave(index);
				  },
				  onCancel: function () {
				  }
				});
			});
	        $("body").on('click','.domethod',function(){//isbn业务处理     
	            var target = $(this);
	            var method = target.data('method');
	            var isbninformationid = target.data('isbninformationid');
	            $.confirm({
	                  title: '确认操作',
	                  text: '你确定要这么处理吗？',
	                  onOK: function () {
	                	  IsbnInformation.doBusiness(domethod, isbninformationid);
	                  },
	                  onCancel: function () {
	                  }
	            });
	        });
		},
		// 绑定页面初始化事件结束
		init : function() {
			this.inputConfig = "input[type='hidden'], input[type='text'], select, textarea";
			this.dictConfig = ["GRADE","SUBJECT","TERM","EDTION","HOMEWORK_TYPE","ISBN_MANAGE_STATUS", "ISBN_INFORMATION_STATUS", "ISBN_TREATMENT_OPINION", "ISBN_DISTRIBUTE_TYPE", "ISBN_DISTRIBUTE_STATUS", "ISBN_HAS_ANSWER", "ISBN_VALIDATION"];
			this.dtoList = {}, this.maxDataId = 0, this.workType = $("#workType").val();
			this.bindEvent();
			global.doInitDictData({
				data : this.dictConfig,
				success : this.initBody
			});
		}
	};
	IsbnInformation.init();
	return IsbnInformation;
});